package com.github.yoojia.flow.devices;

import com.github.yoojia.flow.Context;
import com.github.yoojia.flow.PiConfig;
import com.github.yoojia.flow.VirtualDevice;
import com.parkingwang.lang.data.Config;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinPwmOutput;
import com.pi4j.io.gpio.RaspiPin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.github.yoojia.flow.util.ConfigKit.checkRequired;

/**
 * @author 2017 Yoojia Chen (yoojiachen@gmail.com)
 */
public abstract class VirtualPWMDevice extends VirtualDevice {

    private static final String TAG = VirtualDigitOutputDevice.class.getSimpleName();
    private static final Logger LOGGER = LoggerFactory.getLogger(VirtualDigitOutputDevice.class);

    private GpioPinPwmOutput mPWMPin;

    @Override
    public void onInit(Context context, Config configs) throws Exception {
        super.onInit(context, configs);
        checkRequired(configs, PiConfig.NAME_PIN_ADDRESS, TAG);

        final int address = configs.getInt(PiConfig.NAME_PIN_ADDRESS);
        final int defPWMRate = configs.getInt(PiConfig.NAME_PWM_DEF_RATE, 1024);

        LOGGER.info("Init OutputPWMDevice, UUID: {}, Address: {}, DefPWMRate",
                getAddress(),
                address,
                defPWMRate);

        mPWMPin = GpioFactory.getInstance()
                .provisionPwmOutputPin(
                        RaspiPin.getPinByAddress(address),
                        getAddress(),
                        defPWMRate);

        if (mPWMPin == null) {
            throw new IllegalStateException("Fail to bind PWM Output pin: " + address);
        }
    }

    @Override
    public void onStart() {
        // nop
    }

    @Override
    public void onStop() {
        // nop
    }

    public void setPWM(int pwm){
        mPWMPin.setPwm(pwm);
    }

    public void setPWMRage(int rage){
        mPWMPin.setPwmRange(rage);
    }

    public GpioPinPwmOutput getPWMPin() {
        return mPWMPin;
    }
}
